package pinboard.dataLayer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;

public class CommHelper {
    public static <T> T as(Object o, Class<T> tClass) {
        if (o == null) {
            return null;
        }
        return tClass.isInstance(o) ? (T) o : null;
    }

    public static Object cloneObject(Object obj) throws IOException, ClassNotFoundException {
        return deserialize(serialize(obj));
    }

    private static byte[] serialize(Object input) throws IOException {
        ByteArrayOutputStream obj = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(obj);
        out.writeObject(input);
        return obj.toByteArray();
    }

    private static Object deserialize(byte[] input) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bin = new ByteArrayInputStream(input);
        ObjectInputStream stream = new ObjectInputStream(bin);
        Object obj = stream.readObject();
        return obj;
    }
}
